'''
太健康·百万全家桶
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,time
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "太健康·百万全家桶"

    # 生成产品数据
    def genProductInfo(self):

        plan = {
            # 投保对象 子女年龄大于 16 岁
            "planA": {

                # 年龄段 1 - 60
                "year": [str(i) for i in range(16, 61)],
                # 产品代码 家庭款 TPY_ZGDZYYLBX_TD   个人款 TPY_ZGDZYYLBX_GD
                "productCode": ["TPY_ZGDZYYLBX_TD", "TPY_ZGDZYYLBX_GD"],
                # 有无社保 N 无社保 Y 有社保
                "socialSec": ["N", "Y"],
                # 是否存在特殊医疗 planA 包含 planB 不包含
                "specialTre": ["planA", "planB"],
                # 投保对象
                "payObject": ["本人/配偶/子女/父母"]

            },
            # 投保对象子女 年龄小于 16 岁
            "planB": {

                # 年龄段 1 - 60
                "year": [str(i) for i in range(1, 16)],
                # 产品代码 家庭款 TPY_ZGDZYYLBX_TD   个人款 TPY_ZGDZYYLBX_GD
                "productCode": ["TPY_ZGDZYYLBX_TD", "TPY_ZGDZYYLBX_GD"],
                # 有无社保 N 无社保 Y 有社保
                "socialSec": ["N", "Y"],
                # 是否存在特殊医疗 planA 包含 planB 不包含
                "specialTre": ["planA", "planB"],
                # 投保对象
                "payObject": ["子女"]

            },

        }

        for k in plan:

            for v in product(plan[k]["year"], plan[k]["productCode"], plan[k]["socialSec"], plan[k]["specialTre"],
                             plan[k]["payObject"]):
                # 写入数据库
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4]))
                self.mysql._conn.commit()
                print("%s产品信息写入数据库成功" % self.name)

    # 执行爬虫
    def requestJson(self, dt=None):


        data = self.filterInfo( dt )

        print( data )

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=data)

        if r.status_code == 200 and r.json()["flag"] != -1:

            price = Helper.decimalParse( r.json()["grossPremium"] )

            data = {

                    "id":dt["id"],
                    "name":self.name,
                    "price":price
            }
            print( data )
            self.mysql.updatePrice( data )

        else:

            data = {

                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
            }

            self.mysql.updateTask( data )

            print("获取产品价格失败:",dt["id"])


    def filterInfo(self,dt=None):

        if dt["payObject"] == "子女":

            data = {

                "random": "7825",
                "productCode": dt["productCode"],
                "insured_insuredRelatedToApplicantName": "子女",
                "insured_insuredRelatedToApplicant_old": "1",
                "insured_genderName": "",
                "insuredSeq": "0",
                "insuredOperateType": "modi",
                "checkType": "",
                "insured_productTypeId": "1",
                "productTypeId": "1",
                "plan": dt["specialTre"],
                "productSerialNo": "",
                "insured_occupationClass": "",
                "insured_occupationalType": "",
                "insu_third_occupationName": "",
                "insured_insuredRelatedToApplicant": "1",
                "socialSecurity": dt["socialSec"],
                "insured_idType": "1",
                "enterAge": dt["year"]

            }

            return data

        else:

            data = {

                "random": "7825",
                "productCode": dt["productCode"],
                "insured_insuredRelatedToApplicantName": "本人",
                "insured_insuredRelatedToApplicant_old": "1",
                "insured_genderName": "",
                "insuredSeq": "0",
                "insuredOperateType": "modi",
                "checkType": "",
                "insured_productTypeId": "1",
                "productTypeId": "1",
                "plan": dt["specialTre"],
                "productSerialNo": "",
                "insured_occupationClass": "",
                "insured_occupationalType": "",
                "insu_third_occupationName": "",
                "insured_insuredRelatedToApplicant": "1",
                "socialSecurity":dt["socialSec"],
                "insured_idType": "1",
                "enterAge": dt["year"]

            }

            return data



    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }

            self.mysql.updateTask(data)

            self.requestJson(dt)

if __name__ == '__main__':
    s = Spider()
    # s.genProductInfo()
    s.main()